package com.yunhoo.pay.bean;

import com.ibatis.dao.client.DaoManager;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.yunhoo.asset.util.PayCodeConstants;
import com.yunhoo.base.bean.FinancialProjectBean;
import com.yunhoo.base.db.dao.DepartmentDao;
import com.yunhoo.base.db.dao.FinancialProjectDao;
import com.yunhoo.base.db.dao.PersonDao;
import com.yunhoo.base.db.impl.BusinessParameterImpl;
import com.yunhoo.pay.db.impl.AbroadGroupImpl;
import com.yunhoo.base.model.Department;
import com.yunhoo.base.model.FinancialProject;
import com.yunhoo.base.model.PayStyle;
import com.yunhoo.base.model.Person;
import com.yunhoo.pay.db.impl.StyleDetailImpl;
import com.yunhoo.pay.db.impl.TraveCostImpl;
import com.yunhoo.pay.db.impl.VoucherPubImpl;
import com.yunhoo.pay.model.AffairFee;
import com.yunhoo.pay.model.BaseFeeItem;
import com.yunhoo.pay.model.Expense;
import com.yunhoo.pay.model.QueryVouchers;
import com.yunhoo.pay.model.StyleDetail;
import com.yunhoo.pay.model.TravelCost;
import com.yunhoo.pay.model.TravelCostPrint;
import com.yunhoo.pay.model.VouCheckInfo;
import com.yunhoo.pay.util.BillNumBuilder;
import com.yunhoo.sys.db.config.DaoConfig;
import com.yunhoo.sys.db.util.IbatisTemplate;
import com.yunhoo.sys.util.common.Disabled;
import com.yunhoo.sys.util.common.LoginParam;
import com.yunhoo.sys.util.common.MoneyUtil;
import com.yunhoo.sys.util.common.NavigationTool;
import com.yunhoo.sys.util.common.Null;
import com.yunhoo.sys.util.common.ToolKit;
import com.yunhoo.sys.login.LoginBean;
import com.yunhoo.sys.util.tree.TreeUtil;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.ValueChangeEvent;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFooter;
import org.apache.poi.hssf.usermodel.HSSFHeader;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.richfaces.component.UIDataTable;
import org.richfaces.event.TreeSelectionChangeEvent;

/**
 *
 * @author Administrator
 */
@ManagedBean(name = "trainput")
@SessionScoped
public class TravelInputBean implements Serializable {

    private List tripaccountlist = new ArrayList();
    private DataModel<Expense> tripaccountModel = new ListDataModel();
    private LinkedList<Expense> linkedli = new LinkedList<Expense>();
    private List<TravelCost> li = new ArrayList<TravelCost>();
    private ListDataModel<TravelCost> model = new ListDataModel<TravelCost>(li);
    private UIDataTable personData = null;
    private Expense exp = new Expense();
    private AffairFee fee = new AffairFee();
    private boolean showAble = true;
    private boolean addOrUpdate = false;
    private boolean deleteable = false;
    private boolean saveOrNot = false;
    private boolean updateOrNot = false;
    private boolean submitOrNot = false;
    private boolean printAble = false;
    private boolean browAble = false;
    private QueryVouchers qta = new QueryVouchers();
    private int index;
    private Disabled dis = new Disabled();
    private List<SelectItem> payStyleList = new ArrayList();
    private String payway;
    private UIDataTable deptData = null;
    private List<Department> deptli = null;
    private DataModel deptModel = new ListDataModel();
    private List<StyleDetail> styleDetail = new ArrayList();
    private TravelCost travel = new TravelCost();
    private Double styleTotal = 0d;
    private List<TravelCostPrint> printLi = new ArrayList<TravelCostPrint>();
    // private List<TravelCost> printLi = null;
    private Double travelTotal = 0d;
    private static DaoManager daom;
    private static DepartmentDao dao;
    private static FinancialProjectDao finProjdao;
    private FinancialProject finProj = null;
    private DataModel<FinancialProject> finProjModel = null;
    private static String nameSpace = "travelcost.";
    private String projParam = "";
    private List<SelectItem> perli = null;
    private static PersonDao perDao;

    public TravelInputBean() {
        daom = DaoConfig.getDaoManager();
        dao = (DepartmentDao) daom.getDao(DepartmentDao.class);
        finProjdao = (FinancialProjectDao) daom.getDao(FinancialProjectDao.class);
        perDao = (PersonDao) daom.getDao(PersonDao.class);
        initStatus();
        initPayStyleList();
        initStyleDetailList();
        initFinProjList();//预算项目列表
    }

    public final void initStatus() {
        saveOrNot = true;
        addOrUpdate = false;
        deleteable = true;
        updateOrNot = true;
        submitOrNot = true;
        showAble = true;
        printAble = true;
        this.setExp(new Expense());
        this.setFee(new AffairFee());
        li = new ArrayList<TravelCost>();
        model.setWrappedData(li);

        initList();

        FacesContext.getCurrentInstance().renderResponse();
    }

    private void initList() {
        linkedli = new LinkedList();
        Map map = new HashMap();
        map.put("cpsn_number", curPerNum().trim());
        map.put("orgCode", curOrgCode().trim());
        map.put("iyear", curIyear());
        tripaccountlist = IbatisTemplate.queryForList(nameSpace + "querytripaccountByPersonName", map);
        linkedli.addAll(tripaccountlist);
    }

    //选择部门
    public void selected(TreeSelectionChangeEvent event) {
        Department dp = (Department) TreeUtil.listener(event);
        exp.getPayDept().setCode(dp.getCode());
        exp.getPayDept().setName(dp.getName());
        if (!Null.check(exp.getPayDept().getCode())) {
            queryPerLi();
        }
    }

    private void queryPerLi() {
        perli = new ArrayList<SelectItem>();
        List<Person> templi = null;
        try {
            Person param = new Person();
            param.setOrgCode(curOrgCode());
            param.setIyear(curIyear());
            param.setDeptCode(exp.getPayDept().getCode());
            templi = perDao.queryListByDept(param);
        } catch (SQLException ex) {
            Logger.getLogger(LoginBean.class.getName()).log(Level.SEVERE, null, ex);
        }
        if (templi != null) {
            for (Person p : templi) {
                perli.add(new SelectItem(p.getCpsn_number().trim(), p.getCpsn_name().trim()));
            }
        }
    }

    private void initFinProjList() {
        if (finProjModel == null) {
            finProjModel = new ListDataModel<FinancialProject>();
        }
        try {
            List<FinancialProject> finli = finProjdao.queryAll(new FinancialProject(true));
            finProjModel.setWrappedData(finli);
        } catch (SQLException ex) {
            Logger.getLogger(FinancialProjectBean.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    //选择预算项目

    public void projSelected() {
        finProj = finProjModel.getRowData();
        exp.getProject().setFinCode(finProj.getFinCode());
        exp.getProject().setFinName(finProj.getFinName());
        exp.getProject().setCostType(finProj.getCostType());
    }

    private void initPayStyleList() {
        List<PayStyle> styleli = AbroadGroupImpl.getPaystyleliNew("1");
        for (PayStyle d : styleli) {
            payStyleList.add(new SelectItem(d.getCode(), d.getName()));
        }
    }

    public final void initStyleDetailList() {
        List<PayStyle> styleli = AbroadGroupImpl.getPaystyleliNew("1");
        styleDetail = new ArrayList();
        for (int i = 0; i < styleli.size(); i++) {
            StyleDetail sd = new StyleDetail();
            sd.setNumber(exp.getNumber());
            sd.setCode(styleli.get(i).getCode());
            sd.setName(styleli.get(i).getName());
            styleDetail.add(sd);
        }
    }

    public void payWayChange(ValueChangeEvent event) {
        String code = (String) event.getNewValue();
        exp.getPayStyle().setCode(code);
        payway = code;
    }

    public void getFirst() {
        if (linkedli.size() == 0) {
            if (tripaccountlist.isEmpty()) {
                saveOrNot = true;
                addOrUpdate = true;
                deleteable = true;
                updateOrNot = true;
                submitOrNot = true;
                showAble = true;
                printAble = true;
                dis.setLast(true);
                dis.setNext(true);
                dis.setPreviouse(true);
                dis.setFirst(true);
                //System.out.println("您尚未录入单据!");
                ToolKit.msgs_info("您尚未录入单据");
                FacesContext.getCurrentInstance().renderResponse();
            } else {
                linkedli.clear();
                linkedli.addAll(tripaccountlist);
                this.setExp(linkedli.getFirst());
                queryPerLi();
                payway = exp.getPayStyle().getCode();
                travelVoucherDetail(exp.getNumber().trim());
                styleDetail = TraveCostImpl.queryStyleDetail(exp.getNumber().trim());
                payStyleTotal();
                submitOrNot = false;
                dis.setFirst(true);
                dis.setPreviouse(true);
                dis.setNext(false);
                dis.setLast(false);
                saveOrNot = true;
                showAble = true;
                updateOrNot = false;
                deleteable = false;
                printAble = false;
                browAble = true;
            }
        } else {
            this.setExp(linkedli.getFirst());
            queryPerLi();
            payway = exp.getPayStyle().getCode();
            travelVoucherDetail(exp.getNumber().trim());
            styleDetail = TraveCostImpl.queryStyleDetail(exp.getNumber().trim());
            payStyleTotal();
            submitOrNot = false;
            dis.setFirst(true);
            dis.setPreviouse(true);
            dis.setNext(false);
            dis.setLast(false);
            saveOrNot = true;
            browAble = true;
            showAble = true;
            updateOrNot = false;
            deleteable = false;
            printAble = false;
        }
        index = 0;
        FacesContext.getCurrentInstance().renderResponse();
    }

    public void getLast() {
        if (linkedli.size() == 0) {
            if (tripaccountlist.isEmpty()) {
                saveOrNot = true;
                addOrUpdate = true;
                deleteable = true;
                updateOrNot = true;
                submitOrNot = true;
                showAble = true;
                printAble = true;
                dis.setLast(true);
                dis.setNext(true);
                dis.setPreviouse(true);
                dis.setFirst(true);
                //System.out.println("您尚未录入单据!");
                ToolKit.msgs_info("您尚未录入单据");
                FacesContext.getCurrentInstance().renderResponse();
            } else {
                linkedli.clear();
                linkedli.addAll(tripaccountlist);
                this.setExp(linkedli.getLast());
                queryPerLi();
                payway = exp.getPayStyle().getCode();
                travelVoucherDetail(exp.getNumber().trim());
                styleDetail = TraveCostImpl.queryStyleDetail(exp.getNumber().trim());
                payStyleTotal();
                submitOrNot = false;
                dis.setFirst(false);
                dis.setPreviouse(false);
                dis.setNext(true);
                dis.setLast(true);
                saveOrNot = true;
                showAble = true;
                updateOrNot = false;
                deleteable = false;
                printAble = false;
                browAble = true;
            }
        } else {
            this.setExp(linkedli.getLast());
            queryPerLi();
            payway = exp.getPayStyle().getCode();
            travelVoucherDetail(exp.getNumber().trim());
            styleDetail = TraveCostImpl.queryStyleDetail(exp.getNumber().trim());
            payStyleTotal();
            submitOrNot = false;
            dis.setFirst(false);
            dis.setPreviouse(false);
            dis.setNext(true);
            dis.setLast(true);
            saveOrNot = true;
            showAble = true;
            browAble = true;
            updateOrNot = false;
            deleteable = false;
            printAble = false;
        }
        index = linkedli.size() - 1;
        FacesContext.getCurrentInstance().renderResponse();
    }

    public void next() {
        if (index < linkedli.size() - 1) {
            index += 1;
            this.setExp(linkedli.get(index));
            queryPerLi();
            payway = exp.getPayStyle().getCode();
            travelVoucherDetail(exp.getNumber().trim());
            styleDetail = TraveCostImpl.queryStyleDetail(exp.getNumber().trim());
            payStyleTotal();
            //System.out.println("this index:" + index);
            dis.setFirst(false);
            dis.setPreviouse(false);
            browAble = true;
        } else {
            //System.out.println("没有了!");
            ToolKit.msgs_info("没有了!");
            dis.setLast(true);
            dis.setNext(true);
            dis.setFirst(false);
            dis.setPreviouse(false);
            FacesContext.getCurrentInstance().renderResponse();
        }
        submitOrNot = false;
        saveOrNot = true;
        showAble = true;
        updateOrNot = false;
        deleteable = false;
        printAble = false;
        FacesContext.getCurrentInstance().renderResponse();
    }

    public void previouse() {
        if (index > 0) {
            index -= 1;
            this.setExp(linkedli.get(index));
            queryPerLi();
            payway = exp.getPayStyle().getCode();
            travelVoucherDetail(exp.getNumber().trim());
            styleDetail = TraveCostImpl.queryStyleDetail(exp.getNumber().trim());
            payStyleTotal();
            //System.out.println("this index:" + index);
            dis.setNext(false);
            dis.setLast(false);
            browAble = true;
        } else {
            //System.out.println("没有了!");
            ToolKit.msgs_info("没有了!");
            dis.setFirst(true);
            dis.setPreviouse(true);
            dis.setNext(false);
            dis.setLast(false);
            FacesContext.getCurrentInstance().renderResponse();
        }
        submitOrNot = false;
        saveOrNot = true;
        showAble = true;
        updateOrNot = false;
        deleteable = false;
        printAble = false;
        FacesContext.getCurrentInstance().renderResponse();
    }

    public void add() {
        saveOrNot = false;
        showAble = false;
        printAble = true;
        addOrUpdate = true;
        deleteable = true;
        updateOrNot = true;
        submitOrNot = true;
        browAble = false;
        exp = new Expense();
        exp.getUser().setCpsn_name(curPerName().trim());
        exp.getDept().setName(curDeptName().trim());
        exp.getPayDept().setCode(curDeptCode().trim());
        exp.getPayDept().setName(curDeptName().trim());
        exp.setNumDate(curLoginDate());
        //exp.setNumber(ToolsMethed.getTravelMaxNumber());
        exp.setOrgCode(curOrgCode().trim());
        exp.getFeePer().setCpsn_number(curPerNum().trim());
        queryPerLi();
        this.setFee(new AffairFee());
        li = new ArrayList();
        model = new ListDataModel(li);
        addLine();
        initStyleDetailList();
        styleTotal = 0d;
        FacesContext.getCurrentInstance().renderResponse();
    }

    public void addLine() {
        List ivls = (ArrayList) this.getModel().getWrappedData();
        if (ivls.size() > 3) {
            ToolKit.msgs_err("费用明细请勿超过4行！");
            return;
        }
        TravelCost line = new TravelCost();
        ivls.add(line);
        model.setWrappedData(ivls);
    }

    public void deleteLine() {
        li.remove(model.getRowData());
    }

    public void deleteLine_() {
        List<TravelCost> travelist = (ArrayList) this.getModel().getWrappedData();
        for (int i = 0; i < travelist.size(); i++) {
            if (travelist.get(i).isDeleteable()) {
                travelist.remove(i);
                i--;
            }
        }
    }

    public void update() {
        showAble = false;
        addOrUpdate = false;
        saveOrNot = false;
        browAble = false;
        reBuildStyleDetaili();
        FacesContext.getCurrentInstance().renderResponse();
    }

    public void reBuildStyleDetaili() {
        styleDetail = TraveCostImpl.queryStyleDetail(exp.getNumber().trim());
        List<PayStyle> styleli = AbroadGroupImpl.getPaystyleliNew("1");
        if (!Null.check(styleli)) {
            for (PayStyle st : styleli) {
                if (!Null.check(styleDetail)) {
                    boolean flag = true;
                    for (StyleDetail sdl : styleDetail) {
                        if (st.getCode().trim().equals(sdl.getCode().trim())) {
                            flag = false;
                        }
                    }
                    if (flag) {
                        StyleDetail sd = new StyleDetail();
                        sd.setNumber(exp.getNumber());
                        sd.setCode(st.getCode());
                        sd.setName(st.getName());
                        styleDetail.add(sd);
                    }
                } else {
                    initStyleDetailList();
                }
            }
        }
        payStyleTotal();
    }

    public void delete() {
        TraveCostImpl.deleteTravel(exp);
        initStatus();
        FacesContext.getCurrentInstance().renderResponse();
    }

    //保存
    public void savetripaccount() {
        SqlMapClient client = IbatisTemplate.getSqlMapClient();
        try {
            client.startTransaction();
            exp.setVoutype("1");
            exp.setNumberStatus("1");
            //新增保存
            if (addOrUpdate) {
                exp.setNumber(getTravelMaxNumber(client));
                exp.getUser().setCpsn_number(curPerNum().trim());
                exp.getDept().setCode(curDeptCode().trim());
                exp.getPayStyle().setCode(payway);
                Double total = 0d;
                Double hotelDays = 0d;
                Double travleDays = 0d;
                Boolean insert = false;
                li = (List<TravelCost>) model.getWrappedData();
                int rowNumber = 0;
                for (TravelCost cost : li) {
                    if (cost.getBeginDate() != null && cost.getEndDate() != null) {
                        cost.setRownumber(++rowNumber);
                        cost.setNumber(exp.getNumber());
                        fee.setNumber(exp.getNumber());
                        cost.setAmount(Null.convert(cost.getAmount()));//交通费金额
                        TravelCost travelnew = new TravelCost();
                        //住宿
                        travelnew.getTravelDetail().getHotelFee().setNumber(exp.getNumber());
                        travelnew.getTravelDetail().getHotelFee().setRownumber(cost.getRownumber());
                        travelnew.getTravelDetail().getHotelFee().setQuantity(cost.getTravelDetail().getHotelFee().getQuantity());
                        travelnew.getTravelDetail().getHotelFee().setAmount(Null.convert(cost.getTravelDetail().getHotelFee().getAmount()));
                        //出差补助
                        travelnew.getTravelDetail().getTravelGrantsFee().setNumber(exp.getNumber());
                        travelnew.getTravelDetail().getTravelGrantsFee().setRownumber(cost.getRownumber());
                        travelnew.getTravelDetail().getTravelGrantsFee().setQuantity(cost.getTravelDetail().getTravelGrantsFee().getQuantity());
                        travelnew.getTravelDetail().getTravelGrantsFee().setAmount(Null.convert(cost.getTravelDetail().getTravelGrantsFee().getAmount()));
                        total += cost.getAmount()
                                + travelnew.getTravelDetail().getHotelFee().getAmount()
                                + travelnew.getTravelDetail().getTravelGrantsFee().getAmount();//统计交通费    
                        insert = true;
                    }
                }
                if (fee != null && fee.getNumber() != null) {
                    fee.getOfficeFee().setNumber(exp.getNumber());
                    fee.getOfficeFee().setAmount(Null.convert(fee.getOfficeFee().getAmount()));
                    fee.getOrderTicketFee().setNumber(exp.getNumber());
                    fee.getOrderTicketFee().setAmount(Null.convert(fee.getOrderTicketFee().getAmount()));
                    fee.getCityTracfficFee().setNumber(exp.getNumber());
                    fee.getCityTracfficFee().setAmount(Null.convert(fee.getCityTracfficFee().getAmount()));
                    fee.getOtherFee().setNumber(exp.getNumber());
                    fee.getOtherFee().setAmount(Null.convert(fee.getOtherFee().getAmount()));
                    total += fee.getOfficeFee().getAmount()
                            + fee.getOrderTicketFee().getAmount()
                            + fee.getCityTracfficFee().getAmount()
                            + fee.getOtherFee().getAmount();
                }
                if (insert) {
                    exp.setTotal(total);
                }
                if (insert == false) {
                    //System.out.println("请输入内容");
                }
                TraveCostImpl.insertTravel(client, exp, li, fee);
            }

            //修改保存
            if (!addOrUpdate) {
                Double total = 0d;//统计修改后总金额
                Boolean updateornot = false;//判断是否修改成功

                //先删除记录
                //插入修改后的记录
                //首先迭代插入TravelCost列表里面的记录
                li = (List<TravelCost>) model.getWrappedData();
                int rowNumber = 0;
                for (TravelCost cost : li) {
                    if (cost.getBeginDate() != null && cost.getEndDate() != null) {
                        cost.setRownumber(++rowNumber);
                        cost.setNumber(exp.getNumber());
                        fee.setNumber(exp.getNumber());
                        cost.setAmount(Null.convert(cost.getAmount()));//交通费金额
                        TravelCost travelnew = new TravelCost();
                        //住宿
                        travelnew.getTravelDetail().getHotelFee().setNumber(exp.getNumber());
                        travelnew.getTravelDetail().getHotelFee().setRownumber(cost.getRownumber());
                        travelnew.getTravelDetail().getHotelFee().setQuantity(cost.getTravelDetail().getHotelFee().getQuantity());
                        travelnew.getTravelDetail().getHotelFee().setAmount(Null.convert(cost.getTravelDetail().getHotelFee().getAmount()));
                        //出差补助
                        travelnew.getTravelDetail().getTravelGrantsFee().setNumber(exp.getNumber());
                        travelnew.getTravelDetail().getTravelGrantsFee().setRownumber(cost.getRownumber());
                        travelnew.getTravelDetail().getTravelGrantsFee().setQuantity(cost.getTravelDetail().getTravelGrantsFee().getQuantity());
                        travelnew.getTravelDetail().getTravelGrantsFee().setAmount(Null.convert(cost.getTravelDetail().getTravelGrantsFee().getAmount()));
                        total += cost.getAmount()
                                + travelnew.getTravelDetail().getHotelFee().getAmount()
                                + travelnew.getTravelDetail().getTravelGrantsFee().getAmount();//统计交通费
                        updateornot = true;
                    }
                }
                //插入fee
                if (fee != null && fee.getNumber() != null) {
                    fee.getOfficeFee().setNumber(exp.getNumber());
                    fee.getOfficeFee().setAmount(Null.convert(fee.getOfficeFee().getAmount()));
                    fee.getOrderTicketFee().setNumber(exp.getNumber());
                    fee.getOrderTicketFee().setAmount(Null.convert(fee.getOrderTicketFee().getAmount()));
                    fee.getCityTracfficFee().setNumber(exp.getNumber());
                    fee.getCityTracfficFee().setAmount(Null.convert(fee.getCityTracfficFee().getAmount()));
                    fee.getOtherFee().setNumber(exp.getNumber());
                    fee.getOtherFee().setAmount(Null.convert(fee.getOtherFee().getAmount()));
                    total += fee.getOfficeFee().getAmount()
                            + fee.getOrderTicketFee().getAmount()
                            + fee.getCityTracfficFee().getAmount()
                            + fee.getOtherFee().getAmount();
                }
                //插入报销单记录
                if (updateornot) {
                    exp.setTotal(total);
                    exp.setNumberStatus("1");
                    //TraveCostImpl.updateTravelCostByPerson(exp);//插入报销单目录
                }
                TraveCostImpl.updateTravel(client, exp, li, fee);
                if (updateornot == false) {
                    //System.out.println("请输入内容");
                }
            }
            browAble = true;
            client.commitTransaction();
        } catch (SQLException e) {
        } finally {
            try {
                client.endTransaction();
            } catch (SQLException ex) {
                Logger.getLogger(TravelInputBean.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    //保存支付方式
    public void savePayWay() {
        Map map = new HashMap();
        map.put("number", exp.getNumber());
        StyleDetailImpl.deleteStyleDetail(exp.getNumber().trim());
        for (StyleDetail sd : styleDetail) {
            map.put("code", sd.getCode());
            map.put("name", sd.getName());
            map.put("amount", sd.getAmount());
            map.put("orgCode", curOrgCode().trim());
            if (!Null.check(sd.getAmount())) {
                StyleDetailImpl.insertStyleDetail(map);
//                if (addOrUpdate) {
//                    StyleDetailImpl.insertStyleDetail(map);
//                } else {
//                    StyleDetailImpl.updateStyleDetail(map);
//                }
            }
        }
    }

    public void cancel() {
        exp = new Expense();
        qta = new QueryVouchers();
        initStatus();
        if (!linkedli.isEmpty()) {
            dis.setFirst(false);
            dis.setLast(false);
        }
        FacesContext.getCurrentInstance().renderResponse();
    }

    public String getTravelMaxNumber(SqlMapClient client) throws SQLException {

        String ExpenseMaxNumber = (String) client.queryForObject("travelcost.maxExpensetravelNumber", LoginParam.getOrg().getCode());

        if (ExpenseMaxNumber == null || ExpenseMaxNumber.length() == 0) {
            ExpenseMaxNumber = "000001";
            return ExpenseMaxNumber;
        }
        ExpenseMaxNumber = String.format("%06d%n", Integer.parseInt(ExpenseMaxNumber.trim()) + 1);
        return ExpenseMaxNumber.trim();
    }

    public void saveTrafficFeeVoucher(Expense expense) {
        SqlMapClient client = IbatisTemplate.getSqlMapClient();
        try {
            client.startTransaction();

            //新增保存
            if (addOrUpdate) {

                expense.setNumber(getTravelMaxNumber(client));
                expense.getUser().setCpsn_number(curPerNum().trim());
                expense.getDept().setCode(curDeptCode().trim());
                expense.getPayStyle().setCode(payway);
                Double total = 0d;
                Double hotelDays = 0d;
                Double travleDays = 0d;
                Boolean insert = false;
                li = (List<TravelCost>) model.getWrappedData();
                int rowNumber = 0;
                for (TravelCost cost : li) {
                    if (cost.getBeginDate() != null && cost.getEndDate() != null) {
                        cost.setRownumber(++rowNumber);
                        cost.setNumber(expense.getNumber());
                        fee.setNumber(expense.getNumber());
                        cost.setAmount(Null.convert(cost.getAmount()));//交通费金额
                        TravelCost travelnew = new TravelCost();
                        //住宿
                        travelnew.getTravelDetail().getHotelFee().setNumber(expense.getNumber());
                        travelnew.getTravelDetail().getHotelFee().setRownumber(cost.getRownumber());
                        travelnew.getTravelDetail().getHotelFee().setQuantity(cost.getTravelDetail().getHotelFee().getQuantity());
                        travelnew.getTravelDetail().getHotelFee().setAmount(Null.convert(cost.getTravelDetail().getHotelFee().getAmount()));
                        //出差补助
                        travelnew.getTravelDetail().getTravelGrantsFee().setNumber(expense.getNumber());
                        travelnew.getTravelDetail().getTravelGrantsFee().setRownumber(cost.getRownumber());
                        travelnew.getTravelDetail().getTravelGrantsFee().setQuantity(cost.getTravelDetail().getTravelGrantsFee().getQuantity());
                        travelnew.getTravelDetail().getTravelGrantsFee().setAmount(Null.convert(cost.getTravelDetail().getTravelGrantsFee().getAmount()));
                        total += cost.getAmount()
                                + travelnew.getTravelDetail().getHotelFee().getAmount()
                                + travelnew.getTravelDetail().getTravelGrantsFee().getAmount();//统计交通费    
                        insert = true;
                    }
                }
                if (fee != null && fee.getNumber() != null) {
                    fee.getOfficeFee().setNumber(expense.getNumber());
                    fee.getOfficeFee().setAmount(Null.convert(fee.getOfficeFee().getAmount()));
                    fee.getOrderTicketFee().setNumber(expense.getNumber());
                    fee.getOrderTicketFee().setAmount(Null.convert(fee.getOrderTicketFee().getAmount()));
                    fee.getCityTracfficFee().setNumber(expense.getNumber());
                    fee.getCityTracfficFee().setAmount(Null.convert(fee.getCityTracfficFee().getAmount()));
                    fee.getOtherFee().setNumber(expense.getNumber());
                    fee.getOtherFee().setAmount(Null.convert(fee.getOtherFee().getAmount()));
                    total += fee.getOfficeFee().getAmount()
                            + fee.getOrderTicketFee().getAmount()
                            + fee.getCityTracfficFee().getAmount()
                            + fee.getOtherFee().getAmount();
                }
                if (insert) {
                    expense.setTotal(total);
                }
                if (insert == false) {
                    //System.out.println("请输入内容");
                }
                TraveCostImpl.insertTravel(client, expense, li, fee);
            }

            //修改保存
            if (!addOrUpdate) {
                Double total = 0d;//统计修改后总金额
                Boolean updateornot = false;//判断是否修改成功

                //先删除记录
                //插入修改后的记录
                //首先迭代插入TravelCost列表里面的记录
                li = (List<TravelCost>) model.getWrappedData();
                int rowNumber = 0;
                for (TravelCost cost : li) {
                    if (cost.getBeginDate() != null && cost.getEndDate() != null) {
                        cost.setRownumber(++rowNumber);
                        cost.setNumber(expense.getNumber());
                        fee.setNumber(expense.getNumber());
                        cost.setAmount(Null.convert(cost.getAmount()));//交通费金额
                        TravelCost travelnew = new TravelCost();
                        //住宿
                        travelnew.getTravelDetail().getHotelFee().setNumber(expense.getNumber());
                        travelnew.getTravelDetail().getHotelFee().setRownumber(cost.getRownumber());
                        travelnew.getTravelDetail().getHotelFee().setQuantity(cost.getTravelDetail().getHotelFee().getQuantity());
                        travelnew.getTravelDetail().getHotelFee().setAmount(Null.convert(cost.getTravelDetail().getHotelFee().getAmount()));
                        //出差补助
                        travelnew.getTravelDetail().getTravelGrantsFee().setNumber(expense.getNumber());
                        travelnew.getTravelDetail().getTravelGrantsFee().setRownumber(cost.getRownumber());
                        travelnew.getTravelDetail().getTravelGrantsFee().setQuantity(cost.getTravelDetail().getTravelGrantsFee().getQuantity());
                        travelnew.getTravelDetail().getTravelGrantsFee().setAmount(Null.convert(cost.getTravelDetail().getTravelGrantsFee().getAmount()));
                        total += cost.getAmount()
                                + travelnew.getTravelDetail().getHotelFee().getAmount()
                                + travelnew.getTravelDetail().getTravelGrantsFee().getAmount();//统计交通费
                        updateornot = true;
                    }
                }
                //插入fee
                if (fee != null && fee.getNumber() != null) {
                    fee.getOfficeFee().setNumber(expense.getNumber());
                    fee.getOfficeFee().setAmount(Null.convert(fee.getOfficeFee().getAmount()));
                    fee.getOrderTicketFee().setNumber(expense.getNumber());
                    fee.getOrderTicketFee().setAmount(Null.convert(fee.getOrderTicketFee().getAmount()));
                    fee.getCityTracfficFee().setNumber(expense.getNumber());
                    fee.getCityTracfficFee().setAmount(Null.convert(fee.getCityTracfficFee().getAmount()));
                    fee.getOtherFee().setNumber(expense.getNumber());
                    fee.getOtherFee().setAmount(Null.convert(fee.getOtherFee().getAmount()));
                    total += fee.getOfficeFee().getAmount()
                            + fee.getOrderTicketFee().getAmount()
                            + fee.getCityTracfficFee().getAmount()
                            + fee.getOtherFee().getAmount();
                }
                //插入报销单记录
                if (updateornot) {
                    expense.setTotal(total);
                    exp.setNumberStatus("1");
                    //TraveCostImpl.updateTravelCostByPerson(expense);//插入报销单目录
                }
                TraveCostImpl.updateTravel(client, expense, li, fee);
                if (updateornot == false) {
                    //System.out.println("请输入内容");
                }
            }
            browAble = true;
            client.commitTransaction();
        } catch (SQLException e) {
        } finally {
            try {
                client.endTransaction();
            } catch (SQLException ex) {
                Logger.getLogger(TravelInputBean.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public void submitBill() {
        IbatisTemplate.update("loanbill.updateExpStatus", exp);
        //删除历史审核信息
        VouCheckInfo info = new VouCheckInfo();
        info.setBillNum(exp.getNumber());
        info.setVouType(exp.getVoutype());
        VoucherPubImpl.deleteCheckInfo(info);

        exp.setNumberStatus("0");
        browAble = true;
        addOrUpdate = true;
        ToolKit.msgs_info("单据已提交成功，等待审核!");
    }

    public void rescind() {
        //exp.setMemo("单据撤销");
        Map map = new HashMap();
        map.put("orgCode", curOrgCode().trim());
        map.put("voutype", exp.getVoutype().trim());
        map.put("number", exp.getNumber().trim());
        IbatisTemplate.update("commOper.rescindVoucher", map);
        addOrUpdate = false;
        exp.setNumberStatus("1");
        browAble = true;
        //NavigationTool.getSelectedUrl("/reports/person/querytripaccount.xhtml");
        FacesContext.getCurrentInstance().renderResponse();
    }

    public void show() {
        this.setExp(tripaccountModel.getRowData());
        queryPerLi();
        payway = exp.getPayStyle().getCode();
        index = this.tripaccountModel.getRowIndex();
        linkedli.clear();
        linkedli.addAll(tripaccountlist);
        travelVoucherDetail(exp.getNumber().trim());
        styleDetail = TraveCostImpl.queryStyleDetail(exp.getNumber().trim());
        payStyleTotal();
        submitOrNot = false;
        deleteable = false;
        updateOrNot = false;
        printAble = false;
        showAble = true;
        saveOrNot = true;
        addOrUpdate = false;
        if (index == 0) {
            dis.setFirst(true);
            dis.setPreviouse(true);
            dis.setNext(false);
            dis.setLast(false);
        }
        if (index > 0 && index < linkedli.size() - 1) {
            dis.setFirst(false);
            dis.setLast(false);
            dis.setNext(false);
            dis.setPreviouse(false);
        }
        if (index == linkedli.size() - 1) {
            dis.setLast(true);
            dis.setNext(true);
            dis.setPreviouse(false);
            dis.setFirst(false);
        }
        browAble = true;
        tripaccountModel.setWrappedData(new ArrayList<Expense>());
        NavigationTool.getSelectedUrl("/page/pay/business/person/tripaccount.xhtml");
    }

    // 保存检查
    public void checkandRep() {
        int flag = 0;

        projParam = "1";
        String paramValue = BusinessParameterImpl.queryParamValue(projParam.trim());//1、必填 0、可不必须填写

        if (Null.check(exp.getAffair())) {
            ToolKit.msgs_err("您还没有输入出差事由!");
        } else if (Null.check(exp.getProject().getFinCode()) && paramValue.equals("1")) {
            ToolKit.msgs_err("请选择预算项目!");
        } else if (Null.check(exp.getFeePer().getCpsn_number())) {
            ToolKit.msgs_err("请选择报销人!");
        } else if (Null.check(exp.getAffixAmount())) {
            ToolKit.msgs_err("请填写附件张数!");
        } else if (Null.check(exp.getTotal())) {
            ToolKit.msgs_err("报销费用不能为0!");
        } else if (checkSavePayWay()) {
            ToolKit.msgs_err("请填写至少一种支付方式的支付金额!");
        } else if (styleTotal - exp.getTotal() != 0) {  //- exp.getRepayment();制单环节无还款记录。
            ToolKit.msgs_err("【支付方式】合计金额与报销金额不相等!");
        } else {
            SqlMapClient client = IbatisTemplate.getSqlMapClient();
            try {
                client.startTransaction();

                System.out.println("差旅费 事务 开始 ");

                /* savetripaccount start */
                //savetripaccount();

                exp.setVoutype("1");
                exp.setNumberStatus("1");
                //新增保存
                if (addOrUpdate) {
                    String number = BillNumBuilder.buildNum(client);
                    exp.setNumber(number);
                    exp.getUser().setCpsn_number(curPerNum().trim());
                    exp.getDept().setCode(curDeptCode().trim());
                    exp.getPayStyle().setCode(payway);
                    Double total = 0d;
                    Double hotelDays = 0d;
                    Double travleDays = 0d;
                    Boolean insert = false;
                    li = (List<TravelCost>) model.getWrappedData();
                    int rowNumber = 0;
                    for (TravelCost cost : li) {
                        if (cost.getBeginDate() != null && cost.getEndDate() != null) {
                            cost.setRownumber(++rowNumber);
                            cost.setNumber(exp.getNumber());
                            fee.setNumber(exp.getNumber());
                            cost.setAmount(Null.convert(cost.getAmount()));//交通费金额
                            TravelCost travelnew = new TravelCost();
                            //住宿
                            travelnew.getTravelDetail().getHotelFee().setNumber(exp.getNumber());
                            travelnew.getTravelDetail().getHotelFee().setRownumber(cost.getRownumber());
                            travelnew.getTravelDetail().getHotelFee().setQuantity(cost.getTravelDetail().getHotelFee().getQuantity());
                            travelnew.getTravelDetail().getHotelFee().setAmount(Null.convert(cost.getTravelDetail().getHotelFee().getAmount()));
                            //出差补助
                            travelnew.getTravelDetail().getTravelGrantsFee().setNumber(exp.getNumber());
                            travelnew.getTravelDetail().getTravelGrantsFee().setRownumber(cost.getRownumber());
                            travelnew.getTravelDetail().getTravelGrantsFee().setQuantity(cost.getTravelDetail().getTravelGrantsFee().getQuantity());
                            travelnew.getTravelDetail().getTravelGrantsFee().setAmount(Null.convert(cost.getTravelDetail().getTravelGrantsFee().getAmount()));
                            total += cost.getAmount()
                                    + travelnew.getTravelDetail().getHotelFee().getAmount()
                                    + travelnew.getTravelDetail().getTravelGrantsFee().getAmount();//统计交通费    
                            insert = true;
                        }
                    }
                    if (fee != null && fee.getNumber() != null) {
                        fee.getOfficeFee().setNumber(exp.getNumber());
                        fee.getOfficeFee().setAmount(Null.convert(fee.getOfficeFee().getAmount()));
                        fee.getOrderTicketFee().setNumber(exp.getNumber());
                        fee.getOrderTicketFee().setAmount(Null.convert(fee.getOrderTicketFee().getAmount()));
                        fee.getCityTracfficFee().setNumber(exp.getNumber());
                        fee.getCityTracfficFee().setAmount(Null.convert(fee.getCityTracfficFee().getAmount()));
                        fee.getOtherFee().setNumber(exp.getNumber());
                        fee.getOtherFee().setAmount(Null.convert(fee.getOtherFee().getAmount()));
                        total += fee.getOfficeFee().getAmount()
                                + fee.getOrderTicketFee().getAmount()
                                + fee.getCityTracfficFee().getAmount()
                                + fee.getOtherFee().getAmount();
                    }
                    if (insert) {
                        exp.setTotal(total);
                    }
                    if (insert == false) {
                        //System.out.println("请输入内容");
                    }
                    TraveCostImpl.insertTravel(client, exp, li, fee);
                }

                //修改保存
                if (!addOrUpdate) {
                    Double total = 0d;//统计修改后总金额
                    Boolean updateornot = false;//判断是否修改成功

                    //先删除记录
                    //插入修改后的记录
                    //首先迭代插入TravelCost列表里面的记录
                    li = (List<TravelCost>) model.getWrappedData();
                    int rowNumber = 0;
                    for (TravelCost cost : li) {
                        if (cost.getBeginDate() != null && cost.getEndDate() != null) {
                            cost.setRownumber(++rowNumber);
                            cost.setNumber(exp.getNumber());
                            fee.setNumber(exp.getNumber());
                            cost.setAmount(Null.convert(cost.getAmount()));//交通费金额
                            TravelCost travelnew = new TravelCost();
                            //住宿
                            travelnew.getTravelDetail().getHotelFee().setNumber(exp.getNumber());
                            travelnew.getTravelDetail().getHotelFee().setRownumber(cost.getRownumber());
                            travelnew.getTravelDetail().getHotelFee().setQuantity(cost.getTravelDetail().getHotelFee().getQuantity());
                            travelnew.getTravelDetail().getHotelFee().setAmount(Null.convert(cost.getTravelDetail().getHotelFee().getAmount()));
                            //出差补助
                            travelnew.getTravelDetail().getTravelGrantsFee().setNumber(exp.getNumber());
                            travelnew.getTravelDetail().getTravelGrantsFee().setRownumber(cost.getRownumber());
                            travelnew.getTravelDetail().getTravelGrantsFee().setQuantity(cost.getTravelDetail().getTravelGrantsFee().getQuantity());
                            travelnew.getTravelDetail().getTravelGrantsFee().setAmount(Null.convert(cost.getTravelDetail().getTravelGrantsFee().getAmount()));
                            total += cost.getAmount()
                                    + travelnew.getTravelDetail().getHotelFee().getAmount()
                                    + travelnew.getTravelDetail().getTravelGrantsFee().getAmount();//统计交通费
                            updateornot = true;
                        }
                    }
                    //插入fee
                    if (fee != null && fee.getNumber() != null) {
                        fee.getOfficeFee().setNumber(exp.getNumber());
                        fee.getOfficeFee().setAmount(Null.convert(fee.getOfficeFee().getAmount()));
                        fee.getOrderTicketFee().setNumber(exp.getNumber());
                        fee.getOrderTicketFee().setAmount(Null.convert(fee.getOrderTicketFee().getAmount()));
                        fee.getCityTracfficFee().setNumber(exp.getNumber());
                        fee.getCityTracfficFee().setAmount(Null.convert(fee.getCityTracfficFee().getAmount()));
                        fee.getOtherFee().setNumber(exp.getNumber());
                        fee.getOtherFee().setAmount(Null.convert(fee.getOtherFee().getAmount()));
                        total += fee.getOfficeFee().getAmount()
                                + fee.getOrderTicketFee().getAmount()
                                + fee.getCityTracfficFee().getAmount()
                                + fee.getOtherFee().getAmount();
                    }
                    //插入报销单记录
                    if (updateornot) {
                        exp.setTotal(total);
                        exp.setNumberStatus("1");
                        //TraveCostImpl.updateTravelCostByPerson(exp);//插入报销单目录
                    }
                    TraveCostImpl.updateTravel(client, exp, li, fee);
                    if (updateornot == false) {
                        //System.out.println("请输入内容");
                    }
                }

                /* savetripaccount end */

                /*savePayWay start*/
                //savePayWay();

                Map map = new HashMap();
                map.put("number", exp.getNumber());
                StyleDetailImpl.deleteStyleDetail(client, exp.getNumber().trim());
                for (StyleDetail sd : styleDetail) {
                    map.put("code", sd.getCode());
                    map.put("name", sd.getName());
                    map.put("amount", sd.getAmount());
                    map.put("orgCode", curOrgCode().trim());
                    if (!Null.check(sd.getAmount())) {
                        StyleDetailImpl.insertStyleDetail(client, map);
                    }
                }

                /*savePayWay end*/
                System.out.println("差旅费 事务 关闭");

                client.commitTransaction();
                flag = 1;
            } catch (SQLException e) {

                flag = -1;

                System.out.println("差旅费 事务 异常");

                ToolKit.msgs_err("数据库异常，保存失败！");

                System.out.print(e.getMessage());
            } finally {
                System.out.println("差旅费 finally ");
                try {
                    client.endTransaction();
                } catch (SQLException e) {
                    System.out.println(e.getMessage());
                }
            }
        }

        if (flag == 1) {
            ToolKit.msgs_info("请点击【提交】按钮提交单据并打印本单据!");
            browAble = true;
            submitOrNot = false;
            deleteable = false;
            updateOrNot = false;
            printAble = false;
            showAble = true;
            saveOrNot = true;
            addOrUpdate = false;
            initList();
        }
    }

    //保存支付方式
    public boolean checkSavePayWay() {
        boolean styleisNull = true;
        for (StyleDetail sd : styleDetail) {
            if (!Null.check(sd.getAmount())) {
                styleisNull = false;
            }
        }
        return styleisNull;
    }

    public void calDays() {
        //System.out.println("calDays !!!!!!!!");
        Double hotelDays = 0d;
        li = (List<TravelCost>) model.getWrappedData();
        for (TravelCost cost : li) {
            if (cost.getBeginDate() != null && cost.getEndDate() != null) {
                hotelDays = Double.valueOf((cost.getEndDate().getTime() - cost.getBeginDate().getTime()) / (1000 * 60 * 60 * 24));
                cost.getTravelDetail().getHotelFee().setQuantity(hotelDays);
                cost.getTravelDetail().getTravelGrantsFee().setQuantity(hotelDays);
            }
        }
        //System.out.println("hotelDays+++" + hotelDays);
        model.setWrappedData(li);
    }

    public void calcTotal() {
        Double total = 0d;
        li = (List<TravelCost>) model.getWrappedData();
        for (TravelCost cost : li) {
            if (cost.getBeginDate() != null && cost.getEndDate() != null) {
                total += Null.convert(cost.getAmount())
                        + Null.convert(cost.getTravelDetail().getHotelFee().getAmount())
                        + Null.convert(cost.getTravelDetail().getTravelGrantsFee().getAmount());//统计交通费
            }
        }

        total += Null.convert(fee.getOfficeFee().getAmount())
                + Null.convert(fee.getOrderTicketFee().getAmount())
                + Null.convert(fee.getCityTracfficFee().getAmount())
                + Null.convert(fee.getOtherFee().getAmount());
        exp.setTotal(total);
    }

    public void styleAmountClick(Integer rowKey) {
        //System.out.println("rowKey :" + rowKey);
        styleDetail.get(rowKey).setAmount(exp.getTotal() - styleTotal);
        payStyleTotal();
    }

    public void payStyleTotal() {
        //System.out.println("wwwwww");
        styleTotal = 0d;
        for (StyleDetail s : styleDetail) {
            styleTotal += Null.convert(s.getAmount());//统计支付方式金额
        }
        System.out.println("styleTotal:" + styleTotal);
    }

//选择预算项目
    public void selectProjForQuery() {
        FinancialProject fProj = finProjModel.getRowData();
        qta.getProject().setFinCode(fProj.getFinCode());
        qta.getProject().setFinName(fProj.getFinName());
    }

    public void queryTripAccountForPerson() {
        Map map = new HashMap();
        map.put("cpsn_number", curPerNum().trim());
        map.put("orgCode", curOrgCode().trim());
        map.put("iyear", curIyear());
        map.put("number", qta.getNumber().trim());
        map.put("affair", qta.getAffair().trim());
        map.put("projcode", qta.getProject().getFinCode());
        map.put("numDateStart", qta.getNumDateStart());
        map.put("numDateEnd", qta.getNumDateEnd());
        map.put("auditDateStart", qta.getAuditDateStart());
        map.put("auditDateEnd", qta.getAuditDateEnd());
        map.put("payDateStart", qta.getPayDateStart());
        map.put("payDateEnd", qta.getPayDateEnd());
        map.put("totalStart", qta.getTotalStart());
        map.put("totalEnd", qta.getTotalEnd());
        map.put("checkaccountStart", qta.getCheckaccountStart());
        map.put("checkaccountEnd", qta.getCheckaccountEnd());
        map.put("payaccountStart", qta.getPayaccountStart());
        map.put("payaccountEnd", qta.getPayaccountEnd());
        tripaccountlist = IbatisTemplate.queryForList(nameSpace + "tripaccountqueryForPerson", map);
        tripaccountModel.setWrappedData(tripaccountlist);
        FacesContext.getCurrentInstance().renderResponse();
    }
    //

    public void travelVoucherDetail(String number) {
        //交通费明细
        Map map = new HashMap();
        map.put("number", number);
        List<TravelCost> detail = TraveCostImpl.traficDetail(number);
        for (TravelCost t : detail) {
            map.put("rownumber", t.getRownumber());
            map.put("orgCode", curOrgCode().trim());
            List<BaseFeeItem> detailnew = TraveCostImpl.otherTraticFee(map);
            for (BaseFeeItem b : detailnew) {
                if (b.getFeeDesc().trim().equalsIgnoreCase("hotelFee")) {
                    t.getTravelDetail().setHotelFee(b);
                }
                if (b.getFeeDesc().trim().equalsIgnoreCase("travelGrantsFee")) {
                    t.getTravelDetail().setTravelGrantsFee(b);
                }
            }
        }
        model.setWrappedData(detail);
        // 其他费用
        Map param = new HashMap();
        param.put("number", number);
        param.put("orgCode", curOrgCode().trim());
        List<BaseFeeItem> items = TraveCostImpl.otherTraticFee(param);
        for (BaseFeeItem item : items) {
            if (item.getFeeDesc().trim().equalsIgnoreCase("officeFee")) {
                fee.setOfficeFee(item);
            }
            if (item.getFeeDesc().trim().equalsIgnoreCase("orderTicketFee")) {
                fee.setOrderTicketFee(item);
            }
            if (item.getFeeDesc().trim().equalsIgnoreCase("cityTracfficFee")) {
                fee.setCityTracfficFee(item);
            }

            if (item.getFeeDesc().trim().equalsIgnoreCase("otherFee")) {
                fee.setOtherFee(item);
            }
        }
    }

    public void clearQueryResult(ActionEvent e) {
        tripaccountModel.setWrappedData(new ArrayList<Expense>());
    }

    private List<TravelCostPrint> formateList(List<TravelCost> li) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        printLi = new ArrayList<TravelCostPrint>();
        Double totalTrafficCost = 0d;
        Double totalHotelFee = 0d;
        Double totalTravelGrants = 0d;
        for (TravelCost cost : li) {
            TravelCostPrint ttcost = new TravelCostPrint();
            ttcost.setStartDate(String.valueOf(sdf.format(cost.getBeginDate())));
            ttcost.setEndDate(cost.getEndDate());
            ttcost.setStartLocation(cost.getStartLocation());
            ttcost.setTargetLocation(cost.getTargetLocation());
            ttcost.setSeatType(cost.getFeeDesc().trim());
            ttcost.setTrafficCost(cost.getAmount());
            ttcost.setHotelDays(cost.getTravelDetail().getHotelFee().getQuantity());
            ttcost.setHotelCost(cost.getTravelDetail().getHotelFee().getAmount());
            ttcost.setTravleDays(cost.getTravelDetail().getTravelGrantsFee().getQuantity());
            ttcost.setTravelGrants(cost.getTravelDetail().getTravelGrantsFee().getAmount());
            printLi.add(ttcost);
            //
            totalTrafficCost += Null.convert(cost.getAmount());
            totalHotelFee += Null.convert(cost.getTravelDetail().getHotelFee().getAmount());
            totalTravelGrants += Null.convert(cost.getTravelDetail().getTravelGrantsFee().getAmount());
        }
        TravelCostPrint tcost = new TravelCostPrint();
        tcost.setStartDate("小计");
        tcost.setTrafficCost((totalTrafficCost == 0) ? null : totalTrafficCost);
        tcost.setHotelCost((totalHotelFee == 0) ? null : totalHotelFee);
        tcost.setTravelGrants((totalTravelGrants == 0) ? null : totalTravelGrants);
        printLi.add(tcost);
        travelTotal = ((totalTrafficCost + totalHotelFee + totalTravelGrants) == 0) ? null : (totalTrafficCost + totalHotelFee + totalTravelGrants);
        return printLi;
    }
//    private List<TravelCost> formateList(List<TravelCost> li){
//        printLi = new ArrayList<TravelCost>();
//        printLi.addAll(li);
//        TravelCost tcost = new TravelCost();
//        Double totalTrafficCost = 0d;
//        Double totalHotelFee = 0d;
//        Double totalTravelGrants = 0d;
//        for(TravelCost cost:li){
//            totalTrafficCost += Null.convert(cost.getTrafficCost());
//            totalHotelFee += Null.convert(cost.getHotelFee());
//            totalTravelGrants += Null.convert(cost.getTravelGrants());
//        }
//        tcost.setBeginDate(null);
//        tcost.setEndDate(null);
//        tcost.setTrafficCost((totalTrafficCost==0)?null:totalTrafficCost);
//        tcost.setHotelFee((totalHotelFee==0)?null:totalHotelFee);
//        tcost.setTravelGrants((totalTravelGrants==0)?null:totalTravelGrants);
//        printLi.add(tcost);
//        return printLi;
//    }

//    public void printTravel_() throws Exception {
//        formateList(li);
//        Map map = reportParameter();//parameters
//        ArrayList reportRows = new ArrayList();
//        reportRows.add(printLi);
//
//        JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(printLi);//detail  data
//
//        FacesContext facesContext = FacesContext.getCurrentInstance();
//        facesContext.responseComplete();
//
//        ServletContext scontext = (ServletContext) facesContext.getExternalContext().getContext();
//        JasperPrint jasperPrint = JasperFillManager.fillReport(scontext.getRealPath("/page/pay/print/TravelCost.jasper"), map, dataSource);
//
//        ByteArrayOutputStream baos = new ByteArrayOutputStream();
//        JRPdfExporter exporter = new JRPdfExporter();
//        exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
//        exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, baos);
//        exporter.exportReport();
//        byte[] bytes = baos.toByteArray();
//
//        if (bytes != null && bytes.length > 0) {
//            HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
//            response.setContentType("application/pdf");
//            response.setHeader("Content-disposition", "inline; filename=\"relatorioPorData.pdf\"");
//            response.setContentLength(bytes.length);
//            ServletOutputStream outputStream = response.getOutputStream();
//            outputStream.write(bytes, 0, bytes.length);
//            outputStream.flush();
//            outputStream.close();
//        }
//
//        //System.out.println("Size:" + bytes.length);
//    }
    //处理打印，参数为标准参数
    public void process(OutputStream outStream, Object data) throws Exception {
        printTravel();
    }

    public void printTravel() throws Exception {
        List<TravelCost> list = (List<TravelCost>) model.getWrappedData();
        formateList(list);
        Map map = reportParameter();//parameters
        ArrayList jasperPrintList = new ArrayList();
        FacesContext facesContext = FacesContext.getCurrentInstance();
        ServletContext scontext = (ServletContext) facesContext.getExternalContext().getContext();
        map.put("SUBREPORT_DIR", scontext.getRealPath("/page/pay/print/TravelCost_subreport1.jasper"));

        ArrayList reportRows = new ArrayList();
        reportRows.add(printLi);
        List templi = new ArrayList();
        templi.addAll(printLi);
        if (templi.size() < 6) {
            for (int i = 1; i < 6 - templi.size(); i++) {
                printLi.add(printLi.size() - i, new TravelCostPrint());//空白行
                //System.out.println("i:" + i);
                //System.out.println("printli.size()1:" + printLi.size());
            }
        }
        printLi.add(0, new TravelCostPrint());//空白行
        //System.out.println("printli.size():" + printLi.size());
        JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(printLi);//detail  data

        map.put("travelDetail", dataSource);
        facesContext.responseComplete();

        JasperPrint jasperPrint = JasperFillManager.fillReport(scontext.getRealPath("/page/pay/print/TravelCost.jasper"), map, dataSource);
        jasperPrintList.add(jasperPrint);
//        JasperPrint jasperPrintBill = JasperFillManager.fillReport(scontext.getRealPath("/page/pay/print/bill.jasper"), map);
//        jasperPrintList.add(jasperPrintBill); 

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        JRPdfExporter exporter = new JRPdfExporter();
        //exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
        exporter.setParameter(JRExporterParameter.JASPER_PRINT_LIST, jasperPrintList);
        exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, baos);
        exporter.exportReport();

        byte[] bytes = baos.toByteArray();

        if (bytes != null && bytes.length > 0) {
            HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
            response.setContentType("application/pdf");
            response.setHeader("Content-disposition", "inline; filename=\"relatorioPorData.pdf\"");
            response.setContentLength(bytes.length);
            ServletOutputStream outputStream = response.getOutputStream();
            outputStream.write(bytes, 0, bytes.length);
            outputStream.flush();
            outputStream.close();

        }
    }

    private Map reportParameter() {
        Map map = new HashMap();
        map.put("number", exp.getNumber());
        map.put("numDate", exp.getNumDate());
        map.put("projName", exp.getProject().getFinName());
        map.put("affair", exp.getAffair());
        map.put("bgDate", exp.getBeginDate());
        map.put("edDate", exp.getEndDate());
        map.put("travleDays", Double.valueOf((exp.getEndDate().getTime() - exp.getBeginDate().getTime()) / (1000 * 60 * 60 * 24)) + 1);
        map.put("total", exp.getTotal());
        map.put("payway", setPayStyleStr());//支付方式
        map.put("memo", exp.getMemo());
        map.put("totalCN", MoneyUtil.toChinese(String.valueOf(Null.convert(exp.getTotal() == null ? 0d : exp.getTotal()))));
        map.put("repayment", exp.getRepayment());
        map.put("repayCN", MoneyUtil.toChinese(exp.getRepayment().toString().trim()));
        map.put("remain", exp.getRemain());
        map.put("remainCN", MoneyUtil.toChinese(exp.getRemain().toString().trim()));
        map.put("deptname", exp.getDept().getName());
        map.put("username", exp.getUser().getCpsn_name());
        map.put("affixAmount", exp.getAffixAmount());
        map.put("paycode", exp.getPaycode());
        map.put("travelOffice", fee.getOfficeFee().getAmount());
        map.put("orderTickets", fee.getOrderTicketFee().getAmount());
        map.put("cityTracffic", fee.getCityTracfficFee().getAmount());
        map.put("otherCost", fee.getOtherFee().getAmount());
        map.put("travelTotal", travelTotal);
        map.put("chuChaiRen", exp.getChuChaiRen());
        //补充粘贴单参数
        map.put("cpsn_name", exp.getUser().getCpsn_name());
        map.put("isBaseCost", isBaseCost());
        return map;
    }

    private String isBaseCost() {
        if (exp.getProject() == null || Null.check(exp.getProject().getFinCode())) return "";
        else if (exp.getProject().getCostType() == 1) return "1";
        else if (exp.getProject().getCostType() == 0) return "0";
        else return "";
    }

    private String setPayStyleStr() {
        DecimalFormat dcmFmt = new DecimalFormat("0.00");
        String payStyle = "";
        for (StyleDetail style : styleDetail) {
            if (style.getAmount() != null && style.getAmount() != 0) {
                payStyle += style.getName().trim() + ":" + dcmFmt.format(style.getAmount()) + ";\n";
            }
        }
        if (payStyle.length() > 0) {
            return payStyle.substring(0, payStyle.length() - 1);
        }
        return "";
    }

    public void exportExcel() {
        HSSFWorkbook demoWorkBook = new HSSFWorkbook();
        HSSFSheet demoSheet = demoWorkBook.createSheet("个人单据差旅费报销单列表");
        String[] excelColumns = initTabeleHeader();
        List<Expense> rows = tripaccountlist;

        HSSFHeader header = demoSheet.getHeader();
        header.setCenter("个人单据差旅费报销单列表");
        HSSFRow headerRow = demoSheet.createRow(0);
        for (int i = 0; i < excelColumns.length; i++) {
            HSSFCell headerCell = headerRow.createCell((short) i);
            //headerCell.setEncoding(HSSFCell.ENCODING_UTF_16);
            headerCell.setCellValue(excelColumns[i]);
        }
        //填充数据
        int rowIndex = 1;
        for (Expense row : rows) {
            createTableRow(demoWorkBook, demoSheet, row, rowIndex);
            rowIndex++;
        }
        exportExcel(demoWorkBook, demoSheet);

    }

    //初始化表头信息
    public String[] initTabeleHeader() {
        String[] excelColumns = {"单据编号", "单据状态", "单据日期", "出差事由", "报销金额", "预算项目", "核定金额",
            "审核日期", "审核人", "支付金额", "支付方式", "支付日期", "出纳"};
        return excelColumns;
    }

    public static void createTableRow(HSSFWorkbook demoWorkBook, HSSFSheet demoSheet, Expense eit, int rowIndex) {
        //创建第rowIndex行
        CreationHelper createHelper = demoWorkBook.getCreationHelper();
        HSSFCellStyle dstyle = demoWorkBook.createCellStyle();
        dstyle.setDataFormat(createHelper.createDataFormat().getFormat("yyyy-mm-dd"));//格式

        HSSFCell cell = null;
        HSSFRow row = demoSheet.createRow(rowIndex);
        cell = row.createCell(0);
        cell.setCellValue(PayCodeConstants.convertString(eit.getNumber()));
        cell = row.createCell(1);
        cell.setCellValue(PayCodeConstants.convertString(PayCodeConstants.functionNumberStatus().get(eit.getNumberStatus())));
        cell = row.createCell(2);
        cell.setCellValue(PayCodeConstants.convertDate(eit.getNumDate()));
        cell.setCellStyle(dstyle);
        cell = row.createCell(3);
        cell.setCellValue(PayCodeConstants.convertString(eit.getAffair()));
        cell = row.createCell(4);
        cell.setCellValue(PayCodeConstants.convertDouble(eit.getTotal()));
        cell = row.createCell(5);
        cell.setCellValue(PayCodeConstants.convertString(eit.getProject().getFinName()));
        cell = row.createCell(6);
        cell.setCellValue(PayCodeConstants.convertDouble(eit.getCheckaccount()));
        cell = row.createCell(7);
        if (eit.getAuditDate() == null) {
            cell.setCellValue("");
        } else {
            cell.setCellValue(PayCodeConstants.convertDate(eit.getAuditDate()));
            cell.setCellStyle(dstyle);
        }
        cell = row.createCell(8);
        cell.setCellValue(PayCodeConstants.convertString(eit.getAuditor()));
        cell = row.createCell(9);
        cell.setCellValue(PayCodeConstants.convertDouble(eit.getPayaccount()));
        cell = row.createCell(10);
        cell.setCellValue(PayCodeConstants.convertString(eit.getPayStyle().getCode()));
        cell = row.createCell(11);
        if (eit.getPayDate() == null) {
            cell.setCellValue("");
        } else {
            cell.setCellValue(PayCodeConstants.convertDate(eit.getPayDate()));
            cell.setCellStyle(dstyle);
        }
        cell = row.createCell(12);
        cell.setCellValue(PayCodeConstants.convertString(eit.getPayer()));

    }

    public static void exportExcel(HSSFWorkbook demoWorkBook, HSSFSheet demoSheet) {
        try {
            String strfileName = "book.xls";
            FileOutputStream fos = null;
            //导出
            demoSheet.setGridsPrinted(true);//demoSheet
            HSSFFooter footer = demoSheet.getFooter();
            footer.setRight("Page " + HSSFFooter.page() + " of " + HSSFFooter.numPages());
            // 获得JSF上下文环境
            FacesContext context = FacesContext.getCurrentInstance();
            // 获得ServletContext对象
            ServletContext servletContext = (ServletContext) context.getExternalContext().getContext();
            // 取得文件的绝对路径
            String excelName = servletContext.getRealPath("/upload") + "/" + strfileName;//strfileName
            File exportFile = new File(excelName);
            fos = new FileOutputStream(exportFile);//fos
            demoWorkBook.write(fos);//demoWorkBook
            fos.close();

            FacesContext ctx = FacesContext.getCurrentInstance();
            ctx.responseComplete();
            HttpServletResponse httpServletResponse = (HttpServletResponse) ctx.getExternalContext().getResponse();
            ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream();
            httpServletResponse.setHeader("Content-disposition", "attachment; filename=" + strfileName);//strfileName
            httpServletResponse.setContentLength((int) exportFile.length());//exportFile
            httpServletResponse.setContentType("application/x-download");
            //httpServletResponse.setContentType("application/vnd.ms-excel");
            byte[] b = new byte[1024];
            int i = 0;
            FileInputStream fis = new java.io.FileInputStream(exportFile);
            while ((i = fis.read(b)) > 0) {
                servletOutputStream.write(b, 0, i);
            }
            servletOutputStream.flush();
            ctx.responseComplete();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public ListDataModel<TravelCost> getModel() {
        return model;
    }

    public void setModel(ListDataModel<TravelCost> model) {
        this.model = model;
    }

    public List getTripaccountlist() {
        return tripaccountlist;
    }

    public void setTripaccountlist(List tripaccountlist) {
        this.tripaccountlist = tripaccountlist;
    }

    public Expense getExp() {
        return exp;
    }

    public void setExp(Expense exp) {
        this.exp = exp;
    }

    public AffairFee getFee() {
        return fee;
    }

    public void setFee(AffairFee fee) {
        this.fee = fee;
    }

    public boolean isShowAble() {
        return showAble;
    }

    public void setShowAble(boolean showAble) {
        this.showAble = showAble;
    }

    public boolean isAddOrUpdate() {
        return addOrUpdate;
    }

    public void setAddOrUpdate(boolean addOrUpdate) {
        this.addOrUpdate = addOrUpdate;
    }

    public List<TravelCost> getLi() {
        return li;
    }

    public void setLi(List<TravelCost> li) {
        this.li = li;
    }

    public boolean isDeleteable() {
        return deleteable;
    }

    public void setDeleteable(boolean deleteable) {
        this.deleteable = deleteable;
    }

    public boolean isSaveOrNot() {
        return saveOrNot;
    }

    public void setSaveOrNot(boolean saveOrNot) {
        this.saveOrNot = saveOrNot;
    }

    public boolean isUpdateOrNot() {
        return updateOrNot;
    }

    public void setUpdateOrNot(boolean updateOrNot) {
        this.updateOrNot = updateOrNot;
    }

    public boolean isSubmitOrNot() {
        return submitOrNot;
    }

    public void setSubmitOrNot(boolean submitOrNot) {
        this.submitOrNot = submitOrNot;
    }

    public QueryVouchers getQta() {
        return qta;
    }

    public void setQta(QueryVouchers qta) {
        this.qta = qta;
    }

    public Disabled getDis() {
        return dis;
    }

    public void setDis(Disabled dis) {
        this.dis = dis;
    }

    public boolean isPrintAble() {
        return printAble;
    }

    public void setPrintAble(boolean printAble) {
        this.printAble = printAble;
    }

    public List<SelectItem> getPayStyleList() {
        return payStyleList;
    }

    public void setPayStyleList(List<SelectItem> payStyleList) {
        this.payStyleList = payStyleList;
    }

    public String getPayway() {
        return payway;
    }

    public void setPayway(String payway) {
        this.payway = payway;
    }

    public List<Department> getDeptli() {
        return deptli;
    }

    public void setDeptli(List<Department> deptli) {
        this.deptli = deptli;
    }

    public int getIndex() {
        return index;
    }

    public void setIndex(int index) {
        this.index = index;
    }

    public LinkedList<Expense> getLinkedli() {
        return linkedli;
    }

    public void setLinkedli(LinkedList<Expense> linkedli) {
        this.linkedli = linkedli;
    }
    //

    private String curPerNum() {
        return LoginParam.getPer().getCpsn_number();
    }

    private String curPerName() {
        return LoginParam.getPer().getCpsn_name();
    }

    private String curDeptCode() {
        return LoginParam.getDept().getCode();
    }

    private String curDeptName() {
        return LoginParam.getDept().getName();
    }

    private Date curLoginDate() {
        return LoginParam.getLoginDate();
    }

    private Integer curIyear() {
        return LoginParam.getIyear();
    }

    private String curOrgCode() {
        return LoginParam.getOrg().getCode();
    }

    public boolean isBrowAble() {
        return browAble;
    }

    public void setBrowAble(boolean browAble) {
        this.browAble = browAble;
    }

    public UIDataTable getDeptData() {
        return deptData;
    }

    public void setDeptData(UIDataTable deptData) {
        this.deptData = deptData;
    }

    public DataModel getDeptModel() {
        return deptModel;
    }

    public void setDeptModel(DataModel deptModel) {
        this.deptModel = deptModel;
    }

    public UIDataTable getPersonData() {
        return personData;
    }

    public void setPersonData(UIDataTable personData) {
        this.personData = personData;
    }

    public List<TravelCostPrint> getPrintLi() {
        return printLi;
    }

    public void setPrintLi(List<TravelCostPrint> printLi) {
        this.printLi = printLi;
    }

    public List<StyleDetail> getStyleDetail() {
        return styleDetail;
    }

    public void setStyleDetail(List<StyleDetail> styleDetail) {
        this.styleDetail = styleDetail;
    }

    public Double getStyleTotal() {
        if (styleDetail != null) {
            styleTotal = 0d;
            for (StyleDetail s : styleDetail) {
                styleTotal += Null.convert(s.getAmount());//统计支付方式金额
            }
            System.out.println("styleTotal:" + styleTotal);
        }
        return styleTotal;
    }

    public void setStyleTotal(Double styleTotal) {
        this.styleTotal = styleTotal;
    }

    public TravelCost getTravel() {
        return travel;
    }

    public void setTravel(TravelCost travel) {
        this.travel = travel;
    }

    public Double getTravelTotal() {
        return travelTotal;
    }

    public void setTravelTotal(Double travelTotal) {
        this.travelTotal = travelTotal;
    }

    public DataModel<Expense> getTripaccountModel() {
        return tripaccountModel;
    }

    public void setTripaccountModel(DataModel tripaccountModel) {
        this.tripaccountModel = tripaccountModel;
    }

    public FinancialProject getFinProj() {
        return finProj;
    }

    public void setFinProj(FinancialProject finProj) {
        this.finProj = finProj;
    }

    public DataModel<FinancialProject> getFinProjModel() {
        return finProjModel;
    }

    public void setFinProjModel(DataModel<FinancialProject> finProjModel) {
        this.finProjModel = finProjModel;
    }

    public static String getNameSpace() {
        return nameSpace;
    }

    public static void setNameSpace(String nameSpace) {
        TravelInputBean.nameSpace = nameSpace;
    }

    public String getProjParam() {
        return projParam;
    }

    public void setProjParam(String projParam) {
        this.projParam = projParam;
    }

    public List<SelectItem> getPerli() {
        return perli;
    }

    public void setPerli(List<SelectItem> perli) {
        this.perli = perli;
    }
}
